<?php

namespace App\Http\Controllers\Api;

use GuzzleHttp\Client;

class EfutureAccessTokenController extends Controller
{
    const ACCESS_TOKEN_URL = 'http://122.224.86.66:8001/datahub/access_token?appid=test&secret=abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG';
    protected $access_token_key_perfix = 'efuture_token_key';

    public function accessToken($refresh=false,$from='myself')
    {
        $data=\Cache::get('efuture_token_key');

        if($refresh || empty($data)){
            $http = new Client();

            $respon = $http->request('GET',self::ACCESS_TOKEN_URL);

            $res = json_decode($respon->getBody(),true);

            if($res['code']==0 && isset($res['access_token'])){
                $expires = $res['expires_in']??3600;

                $expiredAt = now()->addMinute(floor($expires/60));

                $data = [
                    'access_token'=>$res['access_token'],
                    'expired_at'=>$expiredAt->toDateTimeString()
                ];

                \Cache::put('efuture_token_key',$data,$expiredAt);

            }else{
                $data = $res;
                $this->_log($res,'access_token');
            }
        }

        return $this->response->array($data);
    }

    protected function _log(array $message,string $file_name='efuture')
    {
        $log = new \Monolog\Logger('efuture');
        $logDir = storage_path('logs/efuture/');
        if (!is_dir($logDir)) mkdir($logDir, 0777, true);

        $log->pushHandler(new \Monolog\Handler\StreamHandler($logDir . '/' . $file_name . '.log', \Monolog\Logger::ERROR));

        $log->error('error',$message);
    }
}
